package com.lagou.v4.container;

import com.lagou.v4.LifeCycle;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Kirito
 * @description:
 * @date 2020/05/02
 */
public class Host implements LifeCycle {
    /**
     * localhost
     */
    private String name;

    private String appBase;

    private List<Context> contexts = new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAppBase() {
        return appBase;
    }

    public void setAppBase(String appBase) {
        this.appBase = appBase;
    }

    public List<Context> getContexts() {
        return contexts;
    }

    @Override
    public void init() throws Exception {
        loadContext(appBase);
        for (Context context : contexts) {
            context.init();
        }
    }

    @Override
    public void start() throws Exception {

    }

    private void loadContext(String url) throws Exception {
        File file = new File(url);
        if (file.isFile()) return;
        File[] files = file.listFiles();
        if (files == null || files.length == 0) return;
        for (File f : files) {
            if (f.isFile()) continue;
            Context context = new Context();
            context.setContextPath(f.getName());
            context.setXmlFile(findWebXml(f));
            contexts.add(context);
        }
    }

    private File findWebXml(File f) {
        File[] files = f.listFiles();
        if (files == null || files.length == 0) return null;
        for (File file : files) {
            String fileName = file.getName();
            if (!fileName.equals("WEB-INF")) {
                continue;
            }
            File[] webInfFiles = file.listFiles();
            for (File webInfFile : webInfFiles) {
                if (webInfFile.isFile() && webInfFile.getName().equals("web.xml")) {
                    return webInfFile;
                }
            }
        }
        return null;
    }

    /*private void doLoadContext(File file) throws Exception {
        InputStream is = new FileInputStream(file);
        Document document = new SAXReader().read(is);
        Element rootElement = document.getRootElement();
        List<Element> urlElements = rootElement.selectNodes("//url-pattern");
        if (urlElements != null && urlElements.size() != 0) {
            for (Element urlElement : urlElements) {
                String urlPattern = urlElement.getStringValue();
                Context context = new Context();
                context.setContextPath(urlPattern);
                context.setElement(rootElement);
                contexts.add(context);
            }
        }
    }*/

}
